package bg.btanev.eightyfour.service.pooling;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import bg.btanev.eightyfour.domain.Target;
import bg.btanev.eightyfour.repository.TargetRepository;
import bg.btanev.eightyfour.service.pooling.que.QueItem;
import bg.btanev.eightyfour.service.pooling.que.TargetsUpdateQue;
import bg.btanev.eightyfour.shared.state.TargetState;

/**
 *
 * @author B.Tanev
 *
 */
public class FetchTargetsTask extends AbstractPoolingTask {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = LoggerFactory.getLogger(FetchTargetsTask.class);

	private TargetRepository targetRepository;
	private TargetsUpdateQue targetsUpdateQue;

	public FetchTargetsTask() {
		super("Fetch targets task");
	}

	public void setTargetRepository(TargetRepository targetRepository) {
		this.targetRepository = targetRepository;
	}

	public void setTargetsUpdateQue(TargetsUpdateQue targetsUpdateQue) {
		this.targetsUpdateQue = targetsUpdateQue;
	}

	@Override
	public void run() {
		logger.debug("run() - start"); //$NON-NLS-1$

		List<Target> targets = targetRepository.findAllTargetsToUpdate();
		if (targets != null && targets.size() > 0) {
			for (Target target : targets) {
				addToUpdateQue(target);
				targetRepository.removeFromLocalCache(target);
			}
		}
		targetRepository.clearLocalCache();

		logger.debug("run() - end"); //$NON-NLS-1$
	}

	private void addToUpdateQue(Target target) {
		assert (target != null);

		target.getStatus().changeUpdateState(TargetState.TOPROCESS);
		targetRepository.storeTarget(target);

		targetsUpdateQue.put(new QueItem(target.getId(), target.getStatus().getNextUpdate()));
	}
}
